package edu.whu.puppygo.service.Impl;

import edu.whu.puppygo.assistant.HealthAssistant;
import edu.whu.puppygo.base.HttpResponse;
import edu.whu.puppygo.config.OssConfig;
import edu.whu.puppygo.dao.ConversationDao;
import edu.whu.puppygo.dao.FragmentDao;
import edu.whu.puppygo.dao.PetDao;
import edu.whu.puppygo.dao.UserDao;
import edu.whu.puppygo.dto.FragmentDto;
import edu.whu.puppygo.entity.*;
import edu.whu.puppygo.service.ConversationService;
import edu.whu.puppygo.service.EmbeddingService;
import edu.whu.puppygo.service.VqaService;
import edu.whu.puppygo.util.GlobalUser;
import edu.whu.puppygo.util.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author guanruwang
 * @date 2023/12/1$
 */
@Service
@Slf4j
public class ConversationServiceImpl implements ConversationService {
    @Resource
    private VqaService vqaService;
    @Resource
    private EmbeddingService embeddingService;
    @Resource
    private ConversationDao conversationDao;
    @Resource
    private FragmentDao fragmentDao;
    @Resource
    private OssUtil ossUtil;

    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    private HealthAssistant healthAssistant;
    @Resource
    private PetDao petDao;
    @Resource
    private UserDao userDao;

    @Override
    public Fragment addFragment(FragmentDto fragmentDto) {
        Fragment fragment = new Fragment();
        fragment.setConversationId(fragmentDto.getConversationId());
        fragment.setQuestion(fragmentDto.getQuestion());
        fragment.setStatue(FragmentStatueEnum.DB_INSERT_FINISHED);
        fragment = fragmentDao.save(fragment);
        if (fragmentDto.getImage() != null) {
            MultipartFile image = fragmentDto.getImage();
            String fileName = image.getOriginalFilename();
            String url = ossUtil.uploadFile(fragmentDto.getImage(), OssConfig.getFragmentPic() + fileName);
            fragment.setImgUrl(OssConfig.getFullUrl() + url);
            vqaService.sendMsg(fragment.getImgUrl(), fragmentDto.getQuestion(), fragment.getId());
            return fragmentDao.save(fragment);
        }
        log.info("fragment.getId():{}", fragment.getId());
        embeddingService.sendMsg(fragmentDto.getQuestion(), fragment.getId());

        return fragmentDao.save(fragment);
    }

    @Override
    public Conversation addConversation(Long petId) {
        Conversation conversation = new Conversation();
        conversation.setUserId(GlobalUser.getUser().getId());
        if (petId != null) {
            conversation.setPetId(petId);
        }
        conversation.setName("新建对话" + LocalDateTime.now());
        return conversationDao.save(conversation);
    }
}
